import React, { useEffect, useState } from 'react';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import {
  Grid,
  Typography,
  useMediaQuery,
  Avatar,
  Button
} from '@material-ui/core';
import clsx from 'clsx';
import { Section, SectionAlternate } from 'components/organisms';
import {
  Content,
  Hero,
  SidebarArticles,
  SimilarStories,
  Comment
} from './components';
import { useSelector, useDispatch } from 'react-redux'
import { useHistory } from "react-router-dom";
import { setLoading, setCallbackError } from 'redux/actions/LoadingActions';
import { CKEditor } from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import { Divider } from '@material-ui/core';

import { content } from './data';
import { callGetApi, callPostApi, callUploadFile } from 'utils/networking';

const useStyles = makeStyles(theme => ({
  root: {
    height: '100%',
    width: '100%',
  },
  sidebarNewsletter: {
    marginTop: theme.spacing(4),
    [theme.breakpoints.down('sm')]: {
      marginTop: theme.spacing(2),
    },
  },
  footerNewsletterSection: {
    background: theme.palette.primary.dark,
  },
  avatarContainer: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  listItemText: {
    marginLeft: '10px',
    flex: '0 0 auto',
    marginRight: theme.spacing(2),
    whiteSpace: 'nowrap',
  },
  yourComment: {
    marginTop: '20px',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'start',
  },
  submitBtnContainer: {
    marginTop: '10px',
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'end'
  }
}));

const BlogDetail = () => {
  const classes = useStyles();
  const history = useHistory();
  const dispatch = useDispatch();

  const theme = useTheme();
  const isMd = useMediaQuery(theme.breakpoints.up('md'), {
    defaultMatches: true,
  });

  const [comment, setComment] = useState('');

  const blogItem = useSelector((state) => state.community.communityBlog)
  const category = useSelector((state) => state.community.communityCategoryData)
  const profileData = useSelector((state) => state.auth.profileData)

  const [latestBlogList, setLatestBlogList] = useState([]);
  const [similarBlogList, setSimilarBlogList] = useState([]);
  const [commentList, setCommentList] = useState([]);

  useEffect(() => {
    console.log('use effect');
    if (!blogItem || !blogItem.id || !blogItem.user) {
      if (category) {
        history.push(`/community/${category.id}`);
      } else {
        history.push(`/community`);
      }
    }

    getServerSideProps()
  }, [])

  const getServerSideProps = async () => {
    callGetApi(`blog/related_posts?blog_id=${blogItem.id}`, dispatch, (data) => {
      setLatestBlogList(data.last_5_items.data);
      setSimilarBlogList(data.similar_3_items.data);
      setCommentList(data.comments);
    })
  }

  const loadMoreComments = async () => {
    callGetApi(`blog/comments?blog_id=${blogItem.id}&offset=${commentList.length}`, dispatch, (data) => {
      var uComments = [...commentList, data];
      setCommentList(uComments);
      dispatch(setLoading(false));
    })
  }

  const onChangeComment = (comment) => {
    setComment(comment);
  }

  const submitComment = async () => {
    if (!comment) {
      dispatch(setCallbackError('Please add your comment'));
      return;
    }

    if (!profileData) {
      history.replace('/signin')
      return;
    }

    const data = {
      user_id: profileData.id,
      blog_id: blogItem.id,
      comment_id: 0,
      comment: comment,
    }
    callPostApi('blog/comment', data, dispatch, (data) => {
      setComment('');
      var uComments = [...commentList];
      uComments.push(data);
      setCommentList(uComments);
    })
  }

  const deleted = (commentID) => {
    var uComments = [...commentList];
    for (let i = 0; i < uComments.length; i++) {
      let item = uComments[i];
      if (item.id == commentID) {
        uComments.splice(i, 1);
        break;
      }
    }
    setCommentList(uComments);
  }

  function uploadAdapter(loader) {
    return {
      upload: () => {
        return new Promise((resolve, reject) => {
          loader.file.then((file) => {
            callUploadFile('blog/upload_comment_file', file, dispatch, (data) => {
              resolve({
                default: data
              });
            }, (err) => {
              console.log(err);
              reject(err);
            })
          });
        });
      }
    };
  }

  function uploadPlugin(editor) {
    editor.plugins.get("FileRepository").createUploadAdapter = (loader) => {
      return uploadAdapter(loader);
    };
  }

  return (
    <div className={classes.root}>
      <Hero
        cover={blogItem.thumbnail ? { src: blogItem.thumbnail } : content.cover}
        title={blogItem.title}
        subtitle={blogItem.sub_title ? blogItem.sub_title : ''}
        author={blogItem.user}
        created_at={blogItem.created_at}
      />
      <Section>
        <Grid container spacing={4}>
          <Grid item xs={12} md={8}>
            <Content data={blogItem} />
          </Grid>
          <Grid item xs={12} md={4}>
            <SidebarArticles data={latestBlogList} />
            {/* <SidebarNewsletter className={classes.sidebarNewsletter} /> */}
          </Grid>
        </Grid>
      </Section>

      <SectionAlternate>
        <Grid container spacing={isMd ? 4 : 2}>
          <Typography
            variant="subtitle1"
            color="textPrimary"
            // variant="h5"
            gutterBottom
          >
            Comments
          </Typography>

          {commentList.map((item, index) => (
            <Grid
              item
              xs={12}
              key={index}
              data-aos="fade-up"
              className={classes.gridItem}
            >
              <Comment comment={item}
                deleted={deleted} />
            </Grid>
          ))}

          <Grid item xs={12} data-aos="fade-up">
            <Typography
              variant="subtitle1"
              color="textPrimary"
              // variant={"h5"}
              gutterBottom
            >
              Leave your comment
            </Typography>

            <div className={classes.yourComment}>
              <div className={classes.avatarContainer}>
                <Avatar {...{ src: profileData?profileData.photo:'' }} className={classes.avatar} />
                <Typography variant="body2" color="textPrimary" className={clsx(classes.listItemText, 'menu-item')}>
                  {profileData?profileData.username:''}
                </Typography>
              </div>
              <div style={{ flex: '1' }}>
                <CKEditor
                  config={{
                    extraPlugins: [uploadPlugin]
                  }}
                  editor={ClassicEditor}
                  data={comment}
                  onReady={editor => {
                    // You can store the "editor" and use when it is needed.
                    //console.log('Editor is ready to use!', editor);
                  }}
                  onChange={(event, editor) => {
                    const data = editor.getData();
                    onChangeComment(data);
                    //console.log({ event, editor, data });
                  }}
                  onBlur={(event, editor) => {
                    //console.log('Blur.', editor);
                  }}
                  onFocus={(event, editor) => {
                    //console.log('Focus.', editor);
                  }}
                />
              </div>
              {/* <TextField
                placeholder="Write your comment ..."
                variant="outlined"
                name="description"
                fullWidth
                multiline
                rows={4}
                value={comment}
                onChange={(e) => {
                  onChangeComment(e.target.value);
                }}
              /> */}
            </div>

            <div className={classes.submitBtnContainer} >
              <Button
                variant="contained"
                type="submit"
                color="primary"
                size="large"
                onClick={submitComment}
              >
                Submit
              </Button>
            </div>
          </Grid>
        </Grid>
      </SectionAlternate>

      <Divider />

      <SectionAlternate>
        <SimilarStories data={similarBlogList} />
      </SectionAlternate>

      {/* <SectionAlternate className={classes.footerNewsletterSection}>
        <FooterNewsletter />
      </SectionAlternate> */}
    </div>
  );
};

export default BlogDetail;
